﻿
using System.Web;
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Linq;

namespace CommonLibCore
{
    /// <summary>
    /// 本地缓存操作类
    /// </summary>
    public class CacheHelper 
    {
            
        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static object GetCache(string CacheKey)
        {
            ObjectCache objCache = MemoryCache.Default;
            return objCache[CacheKey];
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objValue)
        {
            ObjectCache objCache = MemoryCache.Default;
            objCache.Add(CacheKey, objValue, new CacheItemPolicy());
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objValue, TimeSpan Timeout)
        {
            ObjectCache objCache = MemoryCache.Default;
            objCache.Add(CacheKey, objValue, new DateTimeOffset(DateTime.Now, Timeout)); ;
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objValue, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            ObjectCache objCache = MemoryCache.Default;
            objCache.Add(CacheKey, objValue, new CacheItemPolicy { AbsoluteExpiration = absoluteExpiration, SlidingExpiration = slidingExpiration });

            //缓存过期时间包括：绝对过期和滑动过期。
            //绝对过期：到了指定时间以后便会失效。
            //滑动过期：在指定时间内无访问请求便失效。
            //实例：
            //绝对过期：
            //objCache.Insert(CacheKey, objValue, null, DateTime.Now.AddMinutes(30), System.Web.Caching.Cache.NoSlidingExpiration);
            //滑动过期：
            //objCache.Insert(CacheKey, objValue, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));            
        }
        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        public static void RemoveAllCache(string CacheKey)
        {
            ObjectCache _cache = MemoryCache.Default;
            _cache.Remove(CacheKey);
        }
        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            ObjectCache _cache = MemoryCache.Default;
            foreach(KeyValuePair<string,object> aaa in _cache.AsEnumerable())
            {
                _cache.Remove(aaa.Key);
            }
        }
    }
}
